/*
 * @Author: xiaosihan 
 * @Date: 2024-05-27 13:49:37 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-05-27 14:50:26
 */
import { ProvincesData } from "@views/home/type";
import { AdditiveBlending, Clock, Group, Mesh, MeshBasicMaterial, QuadraticBezierCurve3, TubeGeometry, Vector3 } from "three";
import threeLoader from "three-base/threeLoader";
import provincesDataJSON from "../provincesData.json";
import flyLine2PNG from "./flyLine2.png";

//飞线分组
export default class FlyLineGroup extends Group {
    constructor() {
        super();
        this.setData(provincesDataJSON);
    }

    //地图偏移量
    offset = new Vector3(-116.468994140625 * 5, 40.25177764892578 * 5, 0.01);

    // 飞线贴图
    flyLineTexture = (() => {
        const texture = threeLoader.getTexture(flyLine2PNG);
        return texture;
    })();

    //飞线材质
    material = new MeshBasicMaterial({
        map: this.flyLineTexture,
        alphaMap: this.flyLineTexture,
        color: 0x2a6f72,
        transparent: true,
        fog: false,
        opacity: 1,
        depthTest: false,
        blending: AdditiveBlending,
    })

    // 设置飞线数据
    setData(provincesDatas: Array<ProvincesData>) {
        this.clear();

        const tubeRadius = 0.03
        const tubeSegments = 32
        const tubeRadialSegments = 8
        const closed = false

        //把东城区作为中心先
        const centerPoint = new Vector3(116.418757, -39.917544, 0).multiplyScalar(5).add(this.offset)

        // 创建飞线
        provincesDatas
            .filter((item, index) => item.value > 10)
            .map((city) => {
                let [x, y] = city.centroid;
                let point = new Vector3(x, -y, 0).multiplyScalar(5).add(this.offset);
                const center = new Vector3()
                center.addVectors(centerPoint, point).multiplyScalar(0.5)
                // 设置曲线中间点的高度
                center.setZ(-1)
                // 三维二次贝塞尔曲线
                const curve = new QuadraticBezierCurve3(centerPoint, center, point)
                // 管道几何体
                const tubeGeometry = new TubeGeometry(curve, tubeSegments, tubeRadius, tubeRadialSegments, closed)
                const mesh = new Mesh(tubeGeometry, this.material);
                mesh.rotation.x = Math.PI / 2
                mesh.position.set(0, 0.5, 0)
                mesh.renderOrder = 21
                this.add(mesh)
            });

    }

    clock = new Clock();

    updateMatrix(): void {
        super.updateMatrix();

        // 贴图偏移动画
        this.flyLineTexture.offset.x -= this.clock.getDelta();
    }
}